const bcrypt = require('bcryptjs')
const { sequelize } = require('../../core/db')
const { Sequelize, Model } = require('sequelize')

class User extends Model {
  static async findByUser (uid) {
    const result = User.findOne({
      where: {
        uid: uid
      }
    })
    return result
  }

  static async checkuser (user) {
    const result = User.findOne({
      where: {
        username: user.username
      }
    })
    return result
  }

  static async verifyUserPassword(username, password) {
    const user = await User.findOne({
      where: {
        username
      }
    })
    if (!user) {
      throw new global.errs.AuthFailed('账号不存在')
    }
    const correct = bcrypt.compareSync(password, user.password)
    if (!correct) {
      throw new global.errs.AuthFailed('密码不正确')
    }
    return user
  }
}

User.init({
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true, // 主键
    autoIncrement: true // 自动增长
  },
  uid: {
    type: Sequelize.STRING
  },
  username: Sequelize.STRING,
  email: {
    type: Sequelize.STRING(128)
  },
  password: {
    type: Sequelize.STRING,
    set (val) {
      const salt = bcrypt.genSaltSync(10)
      const pwd = bcrypt.hashSync(val, salt)
      this.setDataValue('password', pwd)
    }
  }
}, { sequelize, tableName: 'user' })

module.exports = {
  User
}
